package com.jy.modules.cims.common.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.common.service.TCMmCreditPackageService;
import com.jy.modules.cims.component.common.service.TCMmLoanDetailService;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;
import com.jy.modules.cims.data.common.dto.TCMmLoanDetailDTO;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;

/**
 * @classname: TCMmCreditPackageController
 * @description: 定义  债权包 控制层
 * @author:  zhiqiang
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmCreditPackage")
public class TCMmCreditPackageController extends CimsBaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmCreditPackageController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditPackageService")
    private TCMmCreditPackageService service;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
    private TCMmCreditDetailService creditDetailService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
    private TCMmCooperorgDealService cooperorgDealService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmLoanDetailService")
    private TCMmLoanDetailService loanDetailService;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/creditDeal/queryTCMmCreditPackage");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/creditDeal/addTCMmCreditPackage");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditDeal/updateTCMmCreditPackage");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditManage/viewTCMmCreditPackage");
        }else if("toWindowContractPage".equals(operate)){
        	model.setViewName("cims/creditManage/windowTCMmCreditPackage");
        }
        
        
        return model;
    }
    
    /**
     * @author zhiqiang
     * @description:查询分页列表
     * @date 2015-01-07 16:20:41
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmCreditPackage")
    @ResponseBody
    public DataMsg queryListTCMmCreditPackage(HttpServletRequest request, TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmCreditPackageDTO> list = service.searchTCMmCreditPackageByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    

    /**
     * @author zhiqiang
     * @description:新增
     * @date 2015-01-07 16:20:41
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmCreditPackage")
    @ResponseBody
    public DataMsg insertTCMmCreditPackage(HttpServletRequest request, TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	Map<String, Object> searchParams = new HashMap<String, Object>();
        	//dto=null;
        	TCMmCreditPackageDTO  dtoseach=new TCMmCreditPackageDTO();
        	dtoseach.setCooperorgCode(dto.getCooperorgCode());
        	dtoseach.setContractCode(dto.getContractCode());
        	dtoseach.setCreditPackageName(dto.getCreditPackageName());
        	searchParams.put("dto", dtoseach);
            QueryReqBean params = new QueryReqBean();
            params.setSearchParams(searchParams);
        	List<TCMmCreditPackageDTO> list = service.searchTCMmCreditPackage(searchParams);
        	if(list.size()>0){
        		 dataMsg.setMsg("已经存在此记录，请查证");
        		return dataMsg;
        	}
        	dto = (TCMmCreditPackageDTO)super.initDto(dto);
            service.insertTCMmCreditPackage(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:编辑
     * @date 2015-01-07 16:20:41
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmCreditPackage")
    @ResponseBody
    public DataMsg updateTCMmCreditPackage(HttpServletRequest request, TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	//更新债权包表
        	dto = (TCMmCreditPackageDTO)super.initDto(dto);
        	String creditPackageNameOld = dto.getCreditPackageName();
        	if(!dto.getCreditPackageNameNew().equals("")){
        		dto.setCreditPackageName(dto.getCreditPackageNameNew());
        	}
            service.updateTCMmCreditPackage(dto);
            if(!dto.getCreditPackageNameNew().equals("")){
            	 //更新债权明细表
                TCMmCreditDetailDTO tCMmCreditDetailDTO = new TCMmCreditDetailDTO();
                
                tCMmCreditDetailDTO.setCooperorgCode(dto.getCooperorgCode());
                tCMmCreditDetailDTO.setContractCode(dto.getContractCode());
                tCMmCreditDetailDTO.setPackageNum(creditPackageNameOld);
                tCMmCreditDetailDTO.setPackageNumNew(dto.getCreditPackageNameNew());
                
                if(null != dto.getPlanRedeemDate()){
                	tCMmCreditDetailDTO.setPlanRedeemDate(dto.getPlanRedeemDate());
                }
                
                creditDetailService.updateTCMmCreditDetailByCondition(tCMmCreditDetailDTO);
                
              //更新债权交易表
                TCMmCooperorgDealDTO tCMmCooperorgDealDTO = new TCMmCooperorgDealDTO();
                
                tCMmCooperorgDealDTO.setCooperorgCode(dto.getCooperorgCode());
                tCMmCooperorgDealDTO.setContractCode(dto.getContractCode());
                tCMmCooperorgDealDTO.setCreditPackageName(creditPackageNameOld);
                tCMmCooperorgDealDTO.setCreditPackageNameNew(dto.getCreditPackageNameNew());
                
                cooperorgDealService.updateTCMmCooperorgDealByCondition(tCMmCooperorgDealDTO);
                
              //更新贷款明细表
                TCMmLoanDetailDTO tCMmLoanDetailDTO = new TCMmLoanDetailDTO();
                
                tCMmLoanDetailDTO.setCooperorgCode(dto.getCooperorgCode());
                tCMmLoanDetailDTO.setContractCode(dto.getContractCode());
                tCMmLoanDetailDTO.setCreditPackageName(creditPackageNameOld);
                tCMmLoanDetailDTO.setCreditPackageNameNew(dto.getCreditPackageNameNew());
                
                if(null != dto.getPlanRedeemDate()){
                	tCMmLoanDetailDTO.setPlanRedeemDate(dto.getPlanRedeemDate());
                }
                
                loanDetailService.updateTCMmLoanDetailByCondition(tCMmLoanDetailDTO);
            }else if(null != dto.getPlanRedeemDate()){
                
                //更新债权明细表
                TCMmCreditDetailDTO tCMmCreditDetailDTO = new TCMmCreditDetailDTO();
                tCMmCreditDetailDTO.setCooperorgCode(dto.getCooperorgCode());
                tCMmCreditDetailDTO.setContractCode(dto.getContractCode());
                tCMmCreditDetailDTO.setPackageNum(creditPackageNameOld);
                tCMmCreditDetailDTO.setPlanRedeemDate(dto.getPlanRedeemDate());
                creditDetailService.updateTCMmCreditDetailByCondition(tCMmCreditDetailDTO);
                
              //更新贷款明细表
                TCMmLoanDetailDTO tCMmLoanDetailDTO = new TCMmLoanDetailDTO();
                
                tCMmLoanDetailDTO.setCooperorgCode(dto.getCooperorgCode());
                tCMmLoanDetailDTO.setContractCode(dto.getContractCode());
                tCMmLoanDetailDTO.setCreditPackageName(creditPackageNameOld);
                tCMmLoanDetailDTO.setCreditPackageNameNew(dto.getCreditPackageNameNew());
                
                if(null != dto.getPlanRedeemDate()){
                	tCMmLoanDetailDTO.setPlanRedeemDate(dto.getPlanRedeemDate());
                }
                
                loanDetailService.updateTCMmLoanDetailByCondition(tCMmLoanDetailDTO);
            }
          
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:删除
     * @date 2015-01-07 16:20:41
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmCreditPackage")
    @ResponseBody
    public DataMsg deleteTCMmCreditPackage(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	String creditPackageName = (String) this.getParameter("creditPackageName");
   	 	String cooperorgCode = (String) this.getParameter("cooperorgCode");
   		String contractCode = (String) this.getParameter("contractCode");
   	 	dataMsg = super.initDataMsg(dataMsg);
   	 	TCMmCreditPackageDTO  tCMmCreditPackageDTO = new TCMmCreditPackageDTO();
   	 	tCMmCreditPackageDTO.setCreditPackageName(creditPackageName);
   	 	tCMmCreditPackageDTO.setCooperorgCode(cooperorgCode);
   	 	tCMmCreditPackageDTO.setContractCode(contractCode);
   	 	Map<String, Object> paramMap = new HashMap<String, Object>();
   	 	paramMap.put("dto", tCMmCreditPackageDTO);
		try {
			List<TCMmCreditPackageDTO> list = service.deleteTCMmCreditPackageIsExsit(paramMap);
			if(list.size()<=0){
				service.deleteTCMmCreditPackageByPrimaryKey(dto,ids);
				dataMsg.setMsg("删除成功");
			}else {
				dataMsg.setMsg("删除失败！原因：包名正在使用，不允许删除！");
			}
			 
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteTCMmCreditPackage异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author zhiqiang
     * @description:通过主键查询 其明细信息
     * @date 2015-01-07 16:20:41
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmCreditPackageDTO dto = service.queryTCMmCreditPackageByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    @RequestMapping(value = "/queryOneCreditPackageAll")
    @ResponseBody
    public DataMsg queryOneCreditPackageAll(HttpServletRequest request,TCMmCreditPackageDTO dto, @ModelAttribute DataMsg dataMsg) throws AbaboonException{
        
    	try{
//    		String cooperorgCode=this.getParameterString("cooperorgcode");
//    		String contractCode = this.getParameterString("contractCode");
    		
    		Map paramMap = new HashMap<String, Object>(2);
    		paramMap.put("dto", dto);
    		QueryReqBean params = new QueryReqBean();
    	    params.setSearchParams(paramMap);
    	    PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
    		params.setPageParameter(pageInfo);
    	    List<TCMmCreditPackageDTO> dtoList =  service.searchTCMmCreditPackageByPaging(paramMap);
            dataMsg.setData(dtoList);
            dataMsg.setTotalRows(pageInfo.getTotalCount());
    	}catch(Exception e){
    		dataMsg.failed("载入债权包失败");
    		throw new AbaboonException("载入债权包失败",e);
    	}
        return dataMsg;
    }
}
